package com.shixj.ef.core;

import com.shixj.ef.config.FetchConfig;
import com.shixj.ef.execute.HttpFetchExecute;
import com.shixj.ef.execute.HttpFetchExecutor;
import com.shixj.ef.vo.FetchResult;
import org.apache.http.impl.client.CloseableHttpClient;

import java.util.List;

/**
 * Created by shixj on 2017/9/21.
 */
public class DefaultHttpFetcher implements HttpFetcher {
    private FetchConfig fetchConfig;
    private HttpFetchExecute executor;

    public FetchConfig getFetchConfig() {
        return fetchConfig;
    }


    public void setFetchConfig(FetchConfig fetchConfig) {
        this.fetchConfig = fetchConfig;
    }

    public DefaultHttpFetcher(FetchConfig fetchConfig) {
        this.fetchConfig = fetchConfig;
        this.executor = new HttpFetchExecutor(fetchConfig);
    }

    public List<FetchResult> getFetchResults() {
        return this.executor.getFetchResults();
    }

    /**
     * 阻塞队列获取
     *
     * @return
     */
    @Override
    public FetchResult getFetchResult() {
        return this.executor.takeResult();
    }

    private void waitForStop() {
        if(!this.fetchConfig.isAsync())
        while (this.executor.isRun()) {
            try {
                //  LOGGER.info("休眠500毫秒");
                Thread.sleep(this.fetchConfig.getSleepInterval());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void start(CloseableHttpClient httpClient) {
        this.executor.setHttpClient(httpClient);
        this.executor.sendFetch();
        waitForStop();
    }

}
